<template>
  <div class="tenant-detail">

    <!-- 租客信息 -->
    <div class="title">租客信息</div>
    <div class="form">
      <!-- 租户类型 -->
      <div class="form-item">
        <picker
          :range="typeData"
          :value="type"
          @change="typeChange">
          <CustomInput
            title="租户类型"
            placeholder="请选择租户类型"
            :value="formItem.type" />
        </picker>
      </div>
      <!-- 名称 -->
      <div class="form-item">
        <CustomInput
          title="名称"
          placeholder="请填写名称"
          :isInput="true"
          :value="formItem.rentorName"
          @change="rentorNameChange" />
      </div>
      <!-- 证件号 -->
      <div class="form-item">
        <CustomInput
          title="证件号"
          placeholder="请填写证件号"
          :isInput="true"
          :value="formItem.idcards"
          @change="idcardsChange" />
      </div>
      <!-- 联系电话 -->
      <div class="form-item">
        <CustomInput
          inputType="number"
          title="联系电话"
          placeholder="请填写联系电话"
          :isInput="true"
          :value="formItem.rentorPhone"
          @change="rentorPhoneChange" />
      </div>
    </div>

    <!-- 上传证件照 -->
    <div class="title">上传证件照</div>
    <div class="uploadContent">
      <div class="imgs clear">
        <div
          v-if="formItem.__custom_uploadImg && formItem.__custom_uploadImg.length"
          class="uploadImgs pull-left"
          :class="{ isNeedWdith: formItem.__custom_uploadImg.length > 2 }">
          <scroll-view
            scroll-x
            class="uploadImgs-scrollView">
            <div class="uploadImgs-list">
              <div
                v-for="(item, index) in formItem.__custom_uploadImg"
                class="uploadImgs-detail"
                :key="item"
                @tap="scaleImg(item)"
                @longpress="deleteImg(index)">
                <img class="img" mode="aspectFit" :src="item" />
              </div>
            </div>
          </scroll-view>
        </div>
        <div class="uploadIcon pull-left" @tap="uploadImgClick">
          <div class="iconfont icon-tianjiatupian"></div>
          <div>添加照片</div>
        </div>
      </div>
      <div v-if="formItem.__custom_uploadImg && formItem.__custom_uploadImg.length" class="deleteRemind">长按图片以删除</div>
    </div>

    <!-- 保存按钮 -->
    <div class="action">
      <i-button type="primary" @click="actionClick">保存</i-button>
    </div>
  </div>
</template>

<script>
import CustomInput from 'components/CustomInput/CustomInput'
import { mapState } from 'vuex'
import { httpUrl, ERR_OK } from 'api/config'
import { saveData } from 'api/tenantDetail'
import { shareMixin } from 'common/js/mixins'

export default {
  mixins: [shareMixin()],
  components: {
    CustomInput
  },
  computed: {
    ...mapState({
      currentItem: state => state.tenantDetail.currentItem,
      actionKey: state => state.tenantDetail.actionKey
    })
  },
  mounted () {
    this.initData()
  },
  data () {
    return {
      formItem: {},
      type: 0,
      typeData: ['个人', '企业']
    }
  },
  methods: {
    initData () {
      if (this.actionKey === 'edit') {
        this.formItem = JSON.parse(JSON.stringify(this.currentItem))
        this.$set(this.formItem, '__custom_uploadImg', this.formItem.rentorPhotos.split(','))

        this.type = this.typeData.findIndex(item => item === this.formItem.type)
      } else {
        this.type = 0

        this.formItem = {
          type: '',
          rentorName: '',
          idcards: '',
          rentorPhone: '',
          rentorPhotos: '',
          __custom_uploadImg: []
        }
      }
    },
    uploadImgClick () {
      wx.chooseImage({
        success: res => {
          const paths = res.tempFilePaths

          this.uploadAllImg(paths)
        }
      })
    },
    scaleImg (item) {
      wx.previewImage({
        urls: this.formItem.__custom_uploadImg,
        current: item
      })
    },
    deleteImg (index) {
      wx.showModal({
        title: '提示',
        content: '确定要删除该图片吗？',
        success: res => {
          if (res.confirm) {
            const newArr = JSON.parse(JSON.stringify(this.formItem.__custom_uploadImg))
            newArr.splice(index, 1)
            this.formItem.__custom_uploadImg = newArr
          }
        }
      })
    },
    actionClick () {
      if (this.formItem.__custom_uploadImg.length === 0) {
        this.$showToast({
          title: '必须上传证件照',
          icon: 'none'
        })
        return
      }

      const obj = JSON.parse(JSON.stringify(this.formItem))
      obj.rentorPhotos = obj.__custom_uploadImg.join(',')

      this.deleteCustomKey(obj)

      if (obj['createDt']) {
        delete obj['createDt']
      }

      this.saveData(obj)
    },
    deleteCustomKey (obj) {
      for (let key in obj) {
        if (key.indexOf('__custom_') > -1 || obj[key] === null) {
          delete obj[key]
        }
      }
    },
    rentorPhoneChange (e) {
      this.formItem.rentorPhone = e.target.detail.value
    },
    idcardsChange (e) {
      this.formItem.idcards = e.target.detail.value
    },
    rentorNameChange (e) {
      this.formItem.rentorName = e.target.detail.value
    },
    typeChange (e) {
      this.type = e.target.value
      this.formItem.type = this.typeData[this.type]
    },
    async uploadAllImg (paths) {
      this.$showLoading('上传中')

      const imgArr = []

      paths.map(item => {
        imgArr.push(this.uploadImg(item))
      })

      await Promise.all(imgArr)

      this.$hideLoading()
    },
    async uploadImg (filePath) {
      return new Promise((resolve, reject) => {
        wx.uploadFile({
          url: `${httpUrl}/admin/file/fileUpload`,
          filePath,
          name: 'file',
          formData: {},
          success: (res) => {
            const data = JSON.parse(res.data.split('<script>')[0])

            if (data.code === ERR_OK) {
              this.$set(this.formItem, '__custom_uploadImg', [...this.formItem.__custom_uploadImg, `${httpUrl}/${data.data[0]}`])

              resolve(true)
            } else {
              resolve(false)
            }
          },
          fail: res => {
            resolve(false)
          }
        })
      })
    },
    async saveData (data) {
      this.$showLoading('保存中')

      const res = await saveData(data)

      this.$hideLoading()

      if (res.code === ERR_OK) {
        this.$showToast({
          title: '保存成功',
          success: () => {
            wx.navigateBack()
          }
        })
      } else {
        this.$showToast({
          title: (res && res.msg) || '保存失败',
          icon: 'none'
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
  .tenant-detail {
    width: 100%;
    overflow-x: hidden;
    > .title {
      width: 100%;
      line-height: 40px;
      background-color: rgb(248, 248, 248);
      font-size: 14px;
      padding-left: 10px;
    }
    > .form {
      > .form-item {
        border-bottom: 1px solid rgb(238, 238, 238);
      }
    }
    > .uploadContent {
      width: 100%;
      padding: 10px;
      padding-bottom: 0;
      box-sizing: border-box;
      font-size: 14px;
      > .remind {
        color: rgb(219, 219, 219);
        margin-bottom: 15px;
      }
      > .imgs {
        width: 100%;
        overflow: hidden;
        > .uploadImgs {
          height: 80px;
          overflow: hidden;
          padding-right: 5px;
          box-sizing: border-box;
          &.isNeedWdith {
            width: calc(100% - 80px);
          }
          .uploadImgs-scrollView {
            width: 100%;
            height: 100%;
            position: relative;
            .uploadImgs-list {
              width: 100%;
              height: 100%;
              white-space: nowrap;
              .uploadImgs-detail {
                display: inline-block;
                width: 80px;
                height: 80px;
                border-radius: 5px;
                margin-right: 5px;
                position: relative;
                &:nth-last-of-type(1) {
                  margin-right: 0;
                }
                > .img {
                  width: 100%;
                  height: 100%;
                  border-radius: 5px;
                  overflow: hidden;
                }
              }
            }
          }
        }
        > .uploadIcon {
          width: 80px;
          height: 80px;
          border-radius: 5px;
          background-color: rgb(243, 245, 248);
          text-align: center;
          color: rgb(143, 143, 143);
          padding-top: 10px;
          box-sizing: border-box;
          > .iconfont {
            color: rgb(174, 174, 174);
            font-size: 30px;
            margin-bottom: 2px;
          }
        }
      }
      > .deleteRemind {
        margin-top: 15px;
        color: rgb(219, 219, 219);
      }
    }
  }
</style>
